<template>
  <n-form
    class="max-w-[600px]"
    ref="formRef"
    :model="form"
    :rules="rules"
    label-placement="left"
    :label-width="80"
  >
    <n-form-item label="用户昵称" path="nickName">
      <n-input v-model:value="form.nickName" placeholder="请输入用户昵称" />
    </n-form-item>

    <n-form-item label="手机号码" path="phonenumber">
      <n-input v-model:value="form.phonenumber" maxlength="11" placeholder="请输入手机号码" />
    </n-form-item>

    <n-form-item label="邮箱" path="email">
      <n-input v-model:value="form.email" maxlength="50" placeholder="请输入邮箱" />
    </n-form-item>

    <n-form-item label="用户性别">
      <n-radio-group v-model:value="form.sex">
        <template v-for="item in dicts.sys_user_sex" :key="item.value">
          <n-radio :value="item.value">{{ item.label }}</n-radio>
        </template>
      </n-radio-group>
    </n-form-item>

    <n-form-item label=" ">
      <n-button type="primary" @click="submitForm">更新信息</n-button>
    </n-form-item>
  </n-form>
</template>

<script lang="ts" setup>
import { updateProfile } from '@/apis/system/user';
import { useDict } from '@/hooks/useDict';
import { useForm } from '@/hooks/useForm';
import { cloneDeep } from 'lodash-es';
import { useMessage } from 'naive-ui';
import { computed, onUnmounted, watch } from 'vue';

const emits = defineEmits(['updated']);
const props = defineProps<{ data: any }>();
const userInfo = computed(() => cloneDeep(props.data) || {});
const message = useMessage();
const { dicts } = useDict('sys_user_sex');
const { form, setForm, validate } = useForm({
  nickName: null,
  phonenumber: null,
  email: null,
  sex: '0',
});

const rules = {
  userName: [
    { required: true, message: '用户名称不能为空' },
    {
      min: 2,
      max: 20,
      message: '用户名称长度必须介于 2 和 20 之间',
      trigger: 'blur',
    },
  ],
  nickName: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
  email: [
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change'],
    },
  ],
  phonenumber: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur',
    },
  ],
};

watch(
  () => userInfo.value,
  (val) => {
    setForm(val);
  },
);

const submitForm = async () => {
  const errors = await validate();
  if (errors) return;

  try {
    const res: any = await updateProfile(form);
    if (res.code === 200) {
      message.success('更新成功');
      emits('updated');
    }
  } catch (error) {}
};
</script>

<style lang="less" scoped></style>
